package com.chatplus.application.aiprocessor.function;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.functions.FunctionEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

/**
 * 函数实现公共服务
 */
public abstract class TriggerFunctionService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(TriggerFunctionService.class);

    /**
     * 执行函数返回markdown字符串，如果接口直接返回markdown字符串直接调用这个就行，如果是返回json字符串，需要自己解析，继承重写这个方法就行
     *
     * @param functionEntity 函数实体
     * @param arguments      函数参数
     * @return 执行结果
     */
    public String executeReturnMarkdown(FunctionEntity functionEntity, String arguments) {
        String result = commonExecute(functionEntity, arguments);
        if (StringUtils.isEmpty(result)) {
            return "调用函数工具出错：函数返回结果为空";
        }
        return result;
    }

    /**
     * 获取函数渠道（该方法必须设置为 functionEntity.name）,不然获取不到对应的函数，只能执行公共函数
     *
     * @return 函数渠道
     */
    public abstract String getFunctionChannel();

    /**
     * 统一公共的执行函数
     *
     * @param functionEntity 函数实体
     * @param arguments      函数参数
     * @return 执行结果
     */
    protected String commonExecute(FunctionEntity functionEntity, String arguments) {
        String action = functionEntity.getAction();
        String token = functionEntity.getToken();
        if (StringUtils.isEmpty(action) || StringUtils.isEmpty(token)) {
            return "调用函数工具出错：函数未配置";
        }
        HttpResponse response = null;
        try {
            String requestMethod = functionEntity.getRequestMethod();
            if (HttpMethod.GET.name().equals(requestMethod)) {
                JSONObject json = JSONUtil.parseObj(arguments);
                String queryString = HttpUtil.toParams(json); // 将 JSON 对象转换为 GET 参数字符串
                String fullUrl = CharSequenceUtil.format("{}?{}", action, queryString); // 拼接 URL 和 GET 参数
                response = HttpUtil.createGet(fullUrl)
                        .header("Authorization", token)
                        .header("Content-Type", "application/json")
                        .execute();
            } else if (HttpMethod.POST.name().equals(requestMethod)){
                response = HttpUtil.createPost(action)
                        .header("Authorization", token)
                        .header("Content-Type", "application/json")
                        .body(arguments)
                        .execute();
            }
            assert response != null;
            return response.body();
        } catch (Exception e) {
            LOGGER.message("调用函数工具出错")
                    .context("functionEntity", functionEntity)
                    .context("arguments", arguments)
                    .exception(e).error();
            return "调用函数工具出错";
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}
